package com.atguigu.lease.web.app.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private Client client;
    @Autowired
    private UserInfoService userInfoService;

    @Override
    public String getCode(String phone) {
        // 判断手机号是否为空
        if (!StringUtils.hasLength(phone)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }

        // 判断是否发送过于频繁
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        if (stringRedisTemplate.hasKey(key)) {
            throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }

        // 生成验证码
        String code = String.valueOf(new Random().nextInt(900000) + 100000);
        System.out.println(code);

        // 发送短信
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers("15202430163");
        sendSmsRequest.setSignName("阿里云短信测试");
        sendSmsRequest.setTemplateCode("SMS_154950909");
        sendSmsRequest.setTemplateParam("{\"code\":\"" + code + "\"\"}");

        try {
            client.sendSms(sendSmsRequest);
        } catch (Exception e) {
            throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_ERROR);
        }

        // 存入redis，设置过期时间

        stringRedisTemplate.opsForValue().set(key, code,30,TimeUnit.DAYS);
        return code;
    }

    @Override
    public String loginInfo(LoginVo loginVo) {

        // 判断验证码是否过期
        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        if (!stringRedisTemplate.hasKey(key)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }

        // 判断验证码是否正确
        String code = stringRedisTemplate.opsForValue().get(key);
        if (!code.equals(loginVo.getCode())) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }

        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getPhone, loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(wrapper);
        // 判断用户是否存在
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setNickname("尚庭公寓" + loginVo.getPhone());
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setAvatarUrl("http://192.168.126.128:9000/lease/1.jpg");
            userInfoService.save(userInfo);
        }else {
            if (userInfo.getStatus() == BaseStatus.DISABLE) {
                throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
            }
        }


        System.out.println("标点4");

        String jwtToken = JwtUtil.createJwtToken(userInfo.getId());
        System.out.println("标点5");
        return jwtToken;
    }
}
